<template>
  <div class="app-container">
    <el-container>
      <!-- 雅康运维 -->
      <div class="tree-box">
        <el-tree
          node-key="companyId"
          :expand-on-click-node="false"
          highlight-current
          :props="{label: 'companyName'}"
          :data="companyListWithEmpty"
          @node-click="loadCompany"
        />
      </div>
      <el-main style="overflow:hidden" class="main-box">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="负责医院" prop="hospitalId">
            <el-select v-model="queryParams.hospitalId" placeholder="请选择" clearable @change="handleQuery">
              <el-option
                v-for="item in queryHospitalList"
                :key="item.hospitalId"
                :label="item.name"
                :value="item.hospitalId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入"
              maxlength="27"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="staffName">
            <el-input
              v-model="queryParams.staffName"
              placeholder="请输入"
              maxlength="27"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="工号" prop="staffNo">
            <el-input
              v-model="queryParams.staffNo"
              placeholder="请输入"
              maxlength="27"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="人员类型" prop="roleId">
            <el-select v-model="queryParams.roleId" placeholder="请选择" clearable @change="handleQuery">
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basic:staff:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basic:staff:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table ref="dynamicHeightTable" :max-height="tableMaxHeight-84" v-loading="loading" :data="staffList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" width="55" align="center">
            <template slot-scope="scope">
              {{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键ID" align="center" prop="staffId" v-if="false"/>
          <el-table-column label="用户名" align="center" prop="userName" />
          <el-table-column label="姓名" align="center" prop="staffName" />
          <el-table-column label="工号" align="center" prop="staffNo" />
          <el-table-column label="所属公司" align="center" prop="companyName" />
          <el-table-column label="性别" align="center" key="gender" >
            <template v-slot="{row}">{{dict.label.sys_user_sex[row.gender]}}</template>
          </el-table-column>
          <el-table-column label="人员类型" align="center" prop="roleName" />
          <el-table-column label="手机号码" align="center" prop="phoneNumber" />
          <el-table-column label="微信" align="center" prop="oauthId">
            <template v-slot="{ row }">
              <el-tag>{{ bindWeixin(row.oauthId) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="启用登录" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy">
            <template v-slot="{row}">{{labelNickName(row.createBy)}}</template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="科室ID" align="center" prop="departmentId" v-if="false" />
          <el-table-column label="用户id" align="center" prop="userId" v-if="false" />
          <el-table-column label="操作" fixed="right" align="center" width="200px" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basic:staff:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basic:staff:remove']"
              >删除</el-button>

              <el-dropdown>
                <span class="el-dropdown-link">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-lock"
                      @click="handleResetPwd(scope.row)"
                      v-hasPermi="['basic:staff:resetPwd']"
                    >重置密码</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-link"
                      @click="handleUnbindSocial(scope.row)"
                      v-hasPermi="['basic:staff:unbind']"
                      :disabled="!scope.row.oauthId"
                    >解绑微信</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-main>
      <!-- 添加或修改人员信息对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body @keyup.enter.native="submitForm">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" inline @submit.native.prevent>
          <h3 class="title">账号信息</h3>
          <div class="user-info">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model.trim="form.userName" placeholder="请输入" clearable maxlength="27"/>
            </el-form-item>
            <el-form-item label="人员类型" prop="roleId">
              <el-select style="width: 100%;" v-model="form.roleId" placeholder="请选择" clearable @change="resetHospitalId" @clear="resetHospitalId">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="启动登录">
              <el-checkbox v-model="form.status" true-label="0" false-label="1" />
            </el-form-item>
            <el-form-item id="default-password" label-width="101px" v-if="!form.staffId">
              <template slot="label">
                <i class="el-icon-warning-outline"></i>
                <span>默认密码为</span>
              </template>
              <span>{{ form.password }}</span>
            </el-form-item>
            <div class="user-avatar-box">
              <user-avatar :avatar="form.avatar" @on-upload="handleUpload" />
            </div>
          </div>
          <h3 class="title">基本信息</h3>
          <div class="basic-info">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model.trim="form.staffName" placeholder="请输入" clearable maxlength="27"/>
            </el-form-item>
            <el-form-item label="工号" prop="staffNo">
              <el-input v-model.trim="form.staffNo" placeholder="请输入" clearable maxlength="16"/>
            </el-form-item>
            <el-form-item label="所属公司" prop="companyId">
              <el-select v-model="form.companyId" placeholder="请选择" clearable @change="companyChange" :disabled="!!form.staffId">
                <el-option
                  v-for="item in companyOptionList"
                  :key="item.companyId"
                  :label="item.companyName"
                  :value="item.companyId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="负责医院" prop="manageHospitalId" v-if="form.roleId === role[2].value || form.roleId === role[3].value">
              <el-select
                style="width: 100%;"
                v-model="middlewareManageHospitalId"
                placeholder="请选择"
                multiple
                clearable
              >
                <el-option
                  v-for="item in formHospitalList"
                  :key="item.hospitalId"
                  :label="item.name"
                  :value="item.hospitalId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select style="width: 100%;" v-model="form.gender" placeholder="请选择" clearable>
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model.trim="form.phoneNumber" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model.trim="form.email" placeholder="请输入" clearable maxlength="255"/>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary"
          @click="submitForm" @keyup.enter.native="submitForm"
          native-type="submit"
          >确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-container>
    <reset-pwd-dialog v-if="isResetFlag" :isResetFlag = "isResetFlag" :dataForm="dataForm" type="companyStaff"  @changeFlag="changeFlag"/>
  </div>
</template>

<script>
import { optionListHospital } from "@/api/hospital/hospital";
import { optionCompany, selectionCompany } from "@/api/basic/company";
import { listStaff, getStaff, delStaff, addStaff, updateStaff, changeStatus } from "@/api/basic/staff";
import {validEmail, validPhone, validUserName} from '@/utils/validate';
import { unbindSocialInfo } from '@/api/basic/staff';
import { optionRole } from '@/api/system/role';
import UserAvatar from "@/components/Avatar/index";
import ResetPwdDialog from '@/components/ResetPwdDialog'
import { nickName } from '@/mixins/nickName';
import tableMaxHeightRefresh from "@/mixins/tableMaxHeightRefresh";
import { DIC } from "@/const/dict";

const companyType = DIC.postType.find(k => k.prop === 'company')?.value;

export default {
  name: "Staff",
  mixins: [nickName('staffList'),tableMaxHeightRefresh],
  dicts: ['sys_user_sex'],
  components: {
    UserAvatar,
    ResetPwdDialog
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员信息表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 公司列表
      companyList: [],
      // 公司列表(生效合同)
      companyOptionList: [],
      // 人员类型列表
      roleList: [],
      // 查询筛选用医院列表
      queryHospitalList: [],
      // 表单用医院列表
      formHospitalList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        staffNo: undefined,
        staffName: undefined,
        roleId: undefined,
        userName: undefined,
        companyId: undefined
      },
      // 表单参数
      form: {
        staffId: undefined,
        staffNo: undefined,
        staffName: undefined,
        phoneNumber: undefined,
        email: undefined,
        gender: undefined,
        roleId: undefined,
        manageHospitalId: '',
        departmentId: undefined,
        companyId: undefined,
        userId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        userName: undefined,
        status: 1,
        password: 'yk12345678'
      },
      //重置密码的弹窗开关
      isResetFlag: false,
      //重置密码的弹窗表单信息
      dataForm: {},
    };
  },
  created() {
    this.getRoleList();
    this.getQueryHospitalList();
    this.getCompanyList();
    this.getCompanyOptionList()
    this.getList();
  },
  computed: {
    hospitalListWithEmpty() {
      return !this.form.roleId || this.form.roleId === DIC.role[1].value
        ? [{hospitalId: -1, name: '无'}]
        : this.formHospitalList
    },
    role() {return DIC.role},
    companyListWithEmpty() {
      if (this.companyList.length === 1) {
        return this.companyList
      } else {
        return [{companyName: '全部', companyId: ''}].concat(this.companyList)
      }
    },
    bindWeixin() {
      return (oauthId) => oauthId !== null ? '已绑定' : '未绑定'
    },
    middlewareManageHospitalId: {
      get() {
        return typeof this.form.manageHospitalId === 'string' ? this.form.manageHospitalId.split(',').filter(e => !!e) : []
      },
      set(val) {
        if (Array.isArray(val) && val.length > 0) {
          this.$set(this.form, 'manageHospitalId', val.filter(e => !!e).join(','))
        } else {
          this.$set(this.form, 'manageHospitalId', '')
        }
      }
    },
    // 表单校验
    rules() {
      return {
        staffName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        staffNo: [
          { required: true, message: "工号不能为空", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "公司不能为空", trigger: "change" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        roleId: [
          { required: true, message: "人员类型不能为空", trigger: "change" }
        ],
        manageHospitalId: [
          { required: true, message: "负责医院不能为空", trigger: "change" },
        ],
        phoneNumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => {
            if (!value) return callback()
            if (!validPhone(value)) return callback(new Error('请输入正确的手机号码'))
            callback()
          }, trigger: 'blur' }
        ],
        email: [
          { validator: (rule, value, callback) => {
              if (!value) return callback()
              if (!validEmail(value)) return callback(new Error('请输入正确的邮箱地址'))
              callback()
            }, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          { validator: (rule, value, callback) => {
              if (!value) return callback()
              if(!validUserName(value)) return callback(new Error('用户名只能使用英文字母大小写、数字、下划线和加减号'))
              callback()
            }, trigger: "blur"}
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ]
      }
    }
  },
  methods: {
    /** 重置表单的医院id */
    resetHospitalId() {
      // if(!this.form.roleId || this.form.roleId === DIC.role[1].value) {this.form.hospitalId = -1}
      // else {this.form.hospitalId = ''}
      this.$set(this.form, 'manageHospitalId', '')
    },
    /** 所属公司改变 */
    companyChange() {
      this.resetHospitalId()
      this.formHospitalList = []
      if(this.form.companyId) {
        this.getFormHospitalList()
      }
    },
    /** 获取公司列表 */
    getCompanyList() {
      return selectionCompany().then(response => {
        this.companyList = response.data
        return Promise.resolve(response)
      })
    },
    getCompanyOptionList() {
      return optionCompany().then(response => {
        this.companyOptionList = response.data
        return Promise.resolve(response)
      })
    },
    /** 获取公司所有人员类型列表 */
    getRoleList() {
      return optionRole(companyType).then(response => {
        this.roleList = response.data
        return Promise.resolve(response)
      })
    },

    /** 获取查询用医院列表 **/
    getQueryHospitalList() {
      return optionListHospital({companyId: this.queryParams.companyId}).then(response => {
        this.queryHospitalList = response.data
        return Promise.resolve(response)
      })
    },
    /** 获取表单医院列表 **/
    getFormHospitalList() {
      this.formHospitalList = []
      if (!this.form.companyId) {
        return Promise.resolve('公司id为空')
      }
      return optionListHospital({companyId: this.form.companyId}).then(response => {
        this.formHospitalList = response.data
        return Promise.resolve(response)
      })
    },

    /** 根据公司id查询人员信息 **/
    loadCompany(node) {
      this.queryParams.companyId = node.companyId
      this.queryParams.hospitalId = ''
      this.queryParams.pageNum = 1
      this.queryHospitalList = []
      this.getQueryHospitalList()
      this.getList()
    },

    /** 查询人员信息列表 */
    getList() {
      this.loading = true;
      return listStaff(this.queryParams).then(response => {
        this.staffList = response.rows;
        this.total = response.total;
        this.loading = false;
        return Promise.resolve(response)
      });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.form = {
        staffId: undefined,
        staffNo: undefined,
        staffName: undefined,
        phoneNumber: undefined,
        email: undefined,
        gender: undefined,
        roleId: undefined,
        // hospitalId: -1,
        departmentId: undefined,
        companyId: undefined,
        userId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        userName: undefined,
        status: 1,
        password: 'yk12345678'
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.staffId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.formHospitalList = []
      this.title = "添加人员信息";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const staffId = row.staffId || this.ids
      this.formHospitalList = []
      getStaff(staffId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.getFormHospitalList()
        this.open = true;
        this.title = "修改人员信息";
      });
    },

    /** 重置密码操作 */
    handleResetPwd(row) {
      this.isResetFlag = true;
      this.dataForm = row
      // this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   closeOnClickModal: false,
      //   inputPattern: /^.{8,32}$/,
      //   inputErrorMessage: "用户密码长度必须介于 8 和 32 之间",
      //   inputValue: "yk12345678"
      // }).then(({ value }) => {
      //   console.log('2', value)
      //   resetUserPwd(row.userId, value).then(response => {
      //     this.$modal.msgSuccess("修改成功，新密码是：" + value);
      //   });
      // }).catch(() => {});
    },
    changeFlag(){
      this.isResetFlag = false
    },
    /** 解绑微信操作 */
    handleUnbindSocial(row) {
      this.$modal.confirm(`确认解绑${row.userName}用户的微信吗？`).then(() => {
        this.loading = true
        return unbindSocialInfo(row.oauthId)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess("解绑成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.type = companyType;
          if (this.form.staffId != null) {
            updateStaff(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addStaff(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const staffIds = row.staffId || this.ids;
      const tips = row.staffId ? '确认删除该人员吗!' : '确认删除所选择的人员吗!'
      this.$modal.confirm(tips).then(() => {
        this.loading = true;
        return delStaff(staffIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/staff/export', {
        ...this.queryParams
      }, `staff_${new Date().getTime()}.xlsx`)
    },

    /** 上传头像 */
    handleUpload(url) {
      this.form.avatar = url
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
  }
};
</script>
<style scoped>

  .app-container {
    height: calc(100vh - 84px);
  }

  .tree-box,
  .main-box {
    min-height: calc(100vh - 120px);
    background-color: #FFFFFF;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%) ;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .tree-box {
    width: 300px;
    padding: 12px 12px;
    margin-right: 12px;
  }

  .main-box {
    padding: 12px 10px;
  }

  .title {
    height: 30px;
    line-height: 30px;
    border-left: 5px solid #1890FF ;
    background: #F2F7FF;
    padding-left: 10px;
    margin: 0 0 10px 0;
  }

  .user-info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
  }

  .user-avatar-box {
    position: absolute;
    right: 68px;
    top: 0;
  }

  #default-password {
    color: #dcdcdc;
  }

  #default-password i {
    margin-right: 5px;
  }
  /deep/ .el-tree-node__content {
  overflow: hidden;
}

/deep/ .el-tree-node__content>.el-tree-node__label {
  margin-right: 15%;
  max-width: 85%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

/deep/ .is-current .el-tree-node__label {
  word-wrap: break-word;
  word-break: break-all;

  white-space: normal !important;
}
/deep/ .is-current .el-tree-node__content{
  height: auto !important;
}
/deep/ .user-info .el-form-item__error{
  white-space:nowrap;
  word-break:keep-all;
}
</style>
